package com.lx.dao.impl;

import com.lx.dao.TradeDao;
import com.lx.entity.BankCard;
import com.lx.uitl.ConnUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @title: TradeDaoImpl
 * @projectName bankManage
 * @description: TODO
 * @author: yuanChu
 * @date: 2022/5/6  8:36
 */
public class TradeDaoImpl implements TradeDao {

    @Override
    public Integer saveMoney(Double money, String cardId) throws SQLException {
        Connection conn = ConnUtil.getConnection();
        String sql = "update bank_card set card_balance = card_balance + ? where card_id = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setDouble(1, money);
        ps.setString(2, cardId);
        Integer result = ps.executeUpdate();
        ps.close();
        return result;
    }

    @Override
    public Integer takeMoney(Double money,String cardId) throws SQLException {
        Connection conn = ConnUtil.getConnection();
        String sql = "update bank_card set card_balance = card_balance - ? where card_id = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setDouble(1, money);
        ps.setString(2, cardId);
        Integer result = ps.executeUpdate();
        ps.close();
        return result;
    }

    @Override
    public List<BankCard> findBankCardByPhone(String phone) throws SQLException {
        ArrayList<BankCard> list = new ArrayList<>();
        Connection conn = ConnUtil.getConnection();
        String sql = "select * from bank_card JOIN users ON users.user_id = bank_card.users_id where users.user_phone = ? and card_status<>3";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, phone);
        ResultSet rs = ps.executeQuery();
        while(rs.next()){
            BankCard bankCard = new BankCard();
            bankCard.setCardId(rs.getString("card_id"));
            bankCard.setUsersId(rs.getInt("users_id"));
            bankCard.setCardPwd(rs.getString("card_pwd"));
            bankCard.setCardBalance(rs.getDouble("card_balance"));
            bankCard.setCardStatus(rs.getInt("card_status"));
            bankCard.setOpenCard(new java.util.Date(rs.getDate("open_card").getTime()));
            list.add(bankCard);
        }
        return list;
    }


}
